package com.kfgj.hkp.common.coder;

import com.kfgj.hkp.common.BaseEntity;
import com.kfgj.hkp.common.dataaccess.redis.AbstractRedisDao;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * Created by liwensihan on 2017/6/12.
 */
public abstract class AbstractCoder extends AbstractRedisDao<BaseEntity> {

    protected SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    public static String common_code = "gniuu:sequence:coder";

    protected long increment(String redisKey) {
        long id = valueOps.increment(redisKey, 1);
        if (id == 1L) {
            Calendar cal = Calendar.getInstance();
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
                    23, 59, 59);
            cal.set(Calendar.MILLISECOND, 999);
            template.expireAt(redisKey, cal.getTime());
        }
        return id;
    }

    protected String makeCode(String preFix) {
        long id = this.increment(AbstractCoder.common_code);
        StringBuilder sb = new StringBuilder();
        sb.append(sdf.format(new Date()));
        sb.append(StringUtils.leftPad(String.valueOf(id), 6, "0"));
        sb.append(uuidRandom());
        return preFix + sb.toString();
    }

    protected static String uuidRandom() {
        String tmp = UUID.randomUUID().toString();
        tmp = tmp.substring(0, 4);
        return tmp;
    }


}
